import { Form, Button, Col, Row, Input, Select, message, Upload } from 'antd';
import React, { Component } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Productadd, productImgEdit } from '../../../services/auth';
import './index.css';

const { Option } = Select;

// 用于上传的函数
function getBase64(img, callback) {
	const reader = new FileReader();
	reader.addEventListener('load', () => callback(reader.result));
	reader.readAsDataURL(img);
}

function beforeUpload(file) {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
	if (!isJpgOrPng) {
		message.error('You can only upload JPG/PNG file!');
	}
	const isLt4M = file.size / 1024 / 1024 < 4;
	if (!isLt4M) {
		message.error('Image must smaller than 4MB!');
	}
	return isJpgOrPng && isLt4M;
}

export default class CreateProduct extends Component {
	constructor(props) {
		super(props);
		const { handleCreateClick } = this.props;
		this.handleCreateClick = handleCreateClick;
	}
	formRef = React.createRef();
	// 用于上传
	state = {
		loading: false
	};

	handleChange = (info) => {
		this.setState({ file: info.file.originFileObj });
		getBase64(info.file.originFileObj, (imageUrl) =>
			this.setState({
				imageUrl,
				loading: false
			})
		);
	};
	//
	onFinish = (values) => {
		Productadd(values).then(
			(response) => {
				if (response.data.result === 'success') {
					// 有图片就传图
					if (this.state.file) {
						let formData = new FormData();
						formData.append('id', response.data.product_id);
						formData.append('file', this.state.file);
						productImgEdit(formData);
					}
					// 传不传图片都创建成功
					message.success('商品' + response.data.product_id + '已创建成功');
					this.formRef.current.resetFields();
					this.handleCreateClick();
				} else {
					message.info('提交失败，请重试');
				}
			},
			(error) => {
				console.log('数据获取失败', error);
			}
		);
	};
	normFile = (e) => {
		console.log('Upload event:', e);
		if (Array.isArray(e)) {
			return e;
		}
		return e && e.fileList;
	};

	render() {
		// 用于上传
		const { loading, imageUrl } = this.state;
		const uploadButton = (
			<div style={{ height: 135 }}>
				{loading ? <LoadingOutlined /> : <PlusOutlined />}
				<div style={{ marginTop: 20 }}>Upload</div>
			</div>
		);
		return (
			<div>
				<Form layout="vertical" hideRequiredMark onFinish={this.onFinish} ref={this.formRef}>
					<Row gutter={24}>
						<Col span={12}>
							<Form.Item name="name" label="商品名称" rules={[ { required: true, message: '请输入名称' } ]}>
								<Input />
							</Form.Item>
							<Form.Item name="type" label="类型" rules={[ { required: true, message: '请选择类型' } ]}>
								<Select placeholder="必选项">
									<Option value="iPhone">iPhone</Option>
									<Option value="MacBook">MacBook</Option>
									<Option value="iPad">iPad</Option>
									<Option value="Watch">Watch</Option>
									<Option value="AirPods">AirPods</Option>
								</Select>
							</Form.Item>
							<Form.Item name="specification" label="规格" rules={[ { required: true, message: '请输入规格' } ]}>
								<Input />
							</Form.Item>
							<Form.Item name="price" label="价格" rules={[ { required: true, message: '请输入价格' } ]}>
								<Input />
							</Form.Item>
							<Form.Item name="weight" label="净重" rules={[ { required: true, message: '请输入净重' } ]}>
								<Input />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="description" label="详情">
								<Input.TextArea rows={8} />
							</Form.Item>
							<Form.Item name="picture" label="图片">
								<Upload
									name="avatar"
									listType="picture-card"
									className="avatar-uploader"
									showUploadList={false}
									// action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
									beforeUpload={beforeUpload}
									onChange={this.handleChange}
								>
									{imageUrl ? (
										<img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
									) : (
										uploadButton
									)}
								</Upload>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24} />
					<Form.Item>
						<div
							style={{
								textAlign: 'right'
							}}
						>
							<Button onClick={this.onClose} style={{ marginRight: 8 }}>
								取消
							</Button>
							<Button htmlType="reset" style={{ marginRight: 8 }}>
								重置
							</Button>
							<Button type="primary" htmlType="submit">
								提交
							</Button>
						</div>
					</Form.Item>
				</Form>
			</div>
		);
	}
}
